package com.stormragetech.teamwork.spring.service.impl;

import com.stormragetech.common.exception.StormragetechException;
import com.stormragetech.common.utils.StormragetechUtils;
import com.stormragetech.teamwork.common.constant.Constants;
import com.stormragetech.teamwork.common.util.SecurityUtils;
import com.stormragetech.teamwork.entity.TwUser;
import com.stormragetech.teamwork.spring.dao.TwUserMongo;
import com.stormragetech.teamwork.spring.service.TwUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.Date;

/**
 * description: //TODO
 *
 * @author: Xue Bin
 * @version: 1.0.0-SNAPSHOT
 */
@Service
public class TwUserServiceImpl implements TwUserService {

    private final TwUserMongo twUserMongo;

    @Autowired
    public TwUserServiceImpl(TwUserMongo twUserMongo) {
        Assert.notNull(twUserMongo, "TwUserMongo cannot be null !!!");
        this.twUserMongo = twUserMongo;
    }


    @Override
    public void signup(String username, String password, String realname) throws StormragetechException {

        // 初始化盐，生成密码
        //
        String salt = StormragetechUtils.random(1, 8);
        String pass = SecurityUtils.pass(password, salt);

        // 查看用户是否存在
        //
        TwUser entity = twUserMongo.findByUsername(username);
        if (null != entity) {
            throw new StormragetechException(Constants.USER_EX_CODE, Constants.USER_EX_MSG);
        }

        // 构造实体对象，插入mongo
        //
        entity = new TwUser(StormragetechUtils.uuid(), username, pass, salt, realname, new Date(), Constants.UNLOCKED);
        twUserMongo.create(entity);

    }

    @Override
    public void login(String username, String password) throws StormragetechException {

        // 获取用户
        //
        TwUser entity = twUserMongo.findByUsername(username);
        if (null == entity) {
            throw new StormragetechException(Constants.USER_NOEX_CODE, Constants.USER_NOEX_MSG);
        }

        // 验证密码
        //
        String pass = SecurityUtils.pass(password, entity.getSalt());
        if (!entity.getPassword().equals(pass)) {
            throw new StormragetechException(Constants.PASS_ERR_CODE, Constants.PASS_ERR_MSG);
        }

    }
}
